//
//  HELCompulsoryVC.m
//  HandheldELearn
//
//  Created by 陈武琦 on 16/7/12.
//  Copyright © 2016年 陈武琦. All rights reserved.
//
/*
 *          必修／选修
 */
 
typedef NS_ENUM(NSInteger, HELStatusType) {
    HELStatusTypeUnbegin = 0,//0未开始
    HELStatusTypeGoing = 1,//1进行中
    HELStatusTypeCompeleted = 2 //2已完成
    
};
typedef NS_ENUM(NSInteger, HELSortType) {
    HELSortTypeProgress = 1,//1按进度 2按最新 3按热度
    HELSortTypeNew = 2
};

#import "HELCompulsoryVC.h"
#import "HELCompulsoryCell.h"
#import "HELFilterView.h"
#import "HELUserInfoM.h"
#import "HELCourseDetailVC.h"
#import "Masonry.h"
#import "HELSuperTableView.h"

@interface HELCompulsoryVC ()<UITableViewDataSource,UITableViewDelegate, HELFilterViewDelegate>
@property(nonatomic, strong)HELSuperTableView *tableView;
@property(nonatomic, strong)HELFilterView *filterView;
//选修、必修
@property (nonatomic, assign) HELCourseType type;
//选状态
@property (nonatomic, assign) HELStatusType statusType;
//排序
@property (nonatomic, assign) HELSortType sortType;
//是否显示筛选
@property (nonatomic, assign) BOOL isfilter;

@end
static NSString *cellID = @"HELCompulsoryCellID";
@implementation HELCompulsoryVC

- (instancetype)initWithType:(HELCourseType)type {
    if (self = [super init]) {
        _type = type;
        _statusType = -1;
    }

    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleView:self.title];
    self.view.backgroundColor = [UIColor  whiteColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"HELCompulsoryCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellID];
    //筛选
    UIBarButtonItem *FilterItem = [[UIBarButtonItem alloc] initWithTitle:@"筛选" style:UIBarButtonItemStylePlain target:self action:@selector(FilterItemPress)];
    [self.navigationItem setRightBarButtonItem:FilterItem];
    weakSelf_define;
    // 添加下拉刷新头部控件
    [self.tableView wsj_HeaderRefreshBlock:^{
        //请求加载数据
        [weakSelf requestData];
    }];
    
    [self requestData];
    _isfilter = NO;
    [self setNavToBlue];
    
}


- (void)requestData {
    
    
    self.tableView.loading = YES;
    helUserInfo
    NSMutableDictionary *param = [@{@"requiredStatus":@1, @"userId":userInfo.userId} mutableCopy];
    if (self.type == HELcourseTypeCollectStatus) {
        param = [@{@"collectStatus":@1, @"userId":userInfo.userId} mutableCopy];

    }
    if (self.statusType >= 0) {
        param[@"status"] = @(self.statusType);
    }
    
    if (self.sortType > 0) {
        param[@"sortType"] = @(self.sortType);
    }else {
        param[@"sortType"] = @(HELSortTypeNew);
    }
    
    defineWeakSelf;
       [[HELNetworkManager sharedMg] POST:helCompulsoryUrl parameters:param success:^(id responseObject) {
        if (responseObject[@"exception"]) {
            cwqHudRequestError(responseObject[@"exception"]);
        }else {
            NSMutableArray *arr = [HELCompulsoryM mj_objectArrayWithKeyValuesArray:responseObject[@"rows"]];
            
//            for (NSDictionary *dict in responseObject[@"rows"]) {
//                HELCompulsoryM *model = [HELCompulsoryM mj_objectWithKeyValues:dict];
//                [arr addObject:model];
//            }
    
                weakSelf.dataArray = arr;
                [weakSelf.tableView.header endRefreshing];
            
            if (weakSelf.dataArray.count<=0) {
                weakSelf.tableView.loading = NO;
            }
            [weakSelf.tableView reloadData];
            
        }
    } failure:^(NSString *err) {
        
        [weakSelf.tableView.header endRefreshing];
            if (weakSelf.dataArray.count<=0) {
                self.tableView.footer.hidden = YES;
            }else {
                self.tableView.footer.hidden = NO;
            }
        cwqHudRequestError(err);
        if (weakSelf.dataArray.count<=0) {
            weakSelf.tableView.loading = NO;
        }

    }];

}

- (HELSuperTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[HELSuperTableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = kAppBg;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
            }];
    }
    return  _tableView;
}


- (void)FilterItemPress {
    defineWeakSelf;
    self.isfilter = !self.isfilter;
    self.filterView.backgroundColor = [UIColor whiteColor];
    if (weakSelf.isfilter) {
        
        [weakSelf.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).with.offset(80);
        }];
    }else {
    
        [weakSelf.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view).with.offset(0);
        }];
    }
   
    [UIView animateWithDuration:.5 animations:^{
        //更新约束
        [self.view updateConstraintsIfNeeded];
        [self.view layoutIfNeeded];
    }];
}

//筛选按钮
- (HELFilterView *)filterView {
    if (!_filterView) {
        NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"HELFilterView" owner:nil options:nil];
        _filterView = [nibContents lastObject];
        _filterView.backgroundColor = [UIColor blueColor];
        _filterView.delegate = self;
        defineWeakSelf;
        [self.view addSubview:_filterView];
        
        [_filterView mas_makeConstraints:^(MASConstraintMaker *make) {
            //将size设置成(300,300)
            make.size.mas_equalTo(CGSizeMake(kScreenWidth, 80));
            make.left.equalTo(weakSelf.view).with.offset(0);
            make.bottom.equalTo(weakSelf.tableView.mas_top).with.offset(0);

        }];
    }
    return _filterView;


}

#pragma mark - <UITableViewData and UITableDelegate>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 100;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HELCompulsoryCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    HELCompulsoryM *model = self.dataArray[indexPath.row];
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     HELCompulsoryM *model = self.dataArray[indexPath.row];
     HELCourseDetailVC *courseDetailVC = [HELCourseDetailVC new];
    if (self.type == HELcourseTypeRequiredStatus) {
        courseDetailVC.isFromRequiedCourse = YES;
    }
    weakSelf_define;
     courseDetailVC.courseId = [model.tblStudyDataId integerValue];
    courseDetailVC.callBack = ^(HELCourseDetailModel *model){
        [weakSelf requestData];
    };
    
     [self.navigationController pushViewController:courseDetailVC animated:YES];
}
#pragma mark --------HELFilterViewDelegate  筛选--------------------
- (void)HELFilterViewDidSelect:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                    self.statusType = -1;
                    break;
                case 1:
                    self.statusType = HELStatusTypeGoing;
                    break;
                case 2:
                    self.statusType = HELStatusTypeCompeleted;
                    break;
                    
                default:
                    break;
            }
        
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                    self.sortType = HELSortTypeNew;
                    break;
                case 1:
                    self.sortType = HELSortTypeProgress;
                    break;
                default:
                    break;
            }
            
        }
            break;
        default:
            break;
    }

    [self requestData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
